package com.atguigu.sink;

import com.atguigu.bean.WaterSensor;
import com.atguigu.function.WaterSensorMapFunction;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;

public class KafkaSinkWithKeyDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 如果是精准一次，必须开启checkpoint（后续章节介绍）
        env.enableCheckpointing(200, CheckpointingMode.EXACTLY_ONCE);

        SingleOutputStreamOperator<WaterSensor> stringDataStreamSource = env.socketTextStream("10.75.186.206", 9999)
                .map(new WaterSensorMapFunction());

        KafkaSink<WaterSensor> kafkaSink = KafkaSink.<WaterSensor>builder()
                .setBootstrapServers("hadoop102:9092")
                .setRecordSerializer(new KafkaRecordSerializationSchema<WaterSensor>() {
                                         @Nullable
                                         @Override
                                         public ProducerRecord<byte[], byte[]> serialize(WaterSensor waterSensor, KafkaSinkContext kafkaSinkContext, Long aLong) {
                                             byte[] key = waterSensor.getId().getBytes();
                                             byte[] value = waterSensor.getId().getBytes(StandardCharsets.UTF_8);

                                             return new ProducerRecord<>("topic", key, value);
                                         }
                                     }
                )
                .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .build();

        stringDataStreamSource.sinkTo(kafkaSink);

        env.execute();
    }
}
